﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using IKEA.FileExchange.Configuration;

namespace IKEA.FileExchange.Security
{
    public class IPBasedAuthenticationModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
        }

        internal static FileExchangePrincipal AuthenticateByIPAddress(string ipAddress)
        {            

            FileExchangeConfiguration config = FileExchangeConfiguration.LoadConfiguration();

            IPAddressAuthenticationRule authRule = config.FindRule(ipAddress);

            if (authRule == null)
            {
                authRule = config.FindRule("*");
            }

            FileExchangeIdentity identity = new FileExchangeIdentity(authRule.LoginName, true);
            FileExchangePrincipal principal = new FileExchangePrincipal(identity);

            return principal;
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            FileExchangePrincipal p = AuthenticateByIPAddress(HttpContext.Current.Request.UserHostAddress);

            HttpContext.Current.User = p;
        }

        #endregion
    }
}
